package com.wpzf.ndhc.utils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogUtil {

    public static void logToTxt(String log, String url) {
        try {
            String fileName = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".txt";
            String fileUrl = url + fileName;
            Path filePath = Paths.get(fileUrl);

            // 创建文件所在目录（如果目录不存在）
            Path parentPath = filePath.getParent();
            if (parentPath != null && Files.notExists(parentPath)) {
                Files.createDirectories(parentPath);
            }

            // 检查文件是否存在，如果不存在则创建文件
            if (Files.notExists(filePath)) {
                Files.createFile(filePath);
                System.out.println("文件已成功创建。");
            } else {
                System.out.println("文件已存在。");
            }

            // 追加新的日志内容
            try (BufferedWriter bw = Files.newBufferedWriter(filePath, StandardOpenOption.APPEND)) {
                bw.write("[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()) + "]  " + log);
                bw.newLine();
                System.out.println("文件内容已更新成功。");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            System.out.println("创建文件或写入文件时出现异常: " + e.getMessage());
        }
    }

    /*
    public void logText(String log) {
        try {
            File file = new File(logUrl);
            if (!file.exists()) {
                file.createNewFile();
            }
            StringBuilder content = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new FileReader(logUrl))) {
                String line;
                while ((line = br.readLine()) != null) {
                    content.append(line).append("\n");
                }
            }
            String existingContent = content.toString();
            FileWriter write = new FileWriter(logUrl);
            BufferedWriter bw = new BufferedWriter(write);

            // 将读取到的原有内容写入文件
            if (existingContent != null && !existingContent.isEmpty()) {
                bw.write(existingContent + "\n");
            }

            // 写入新的数据
            bw.write(log + "\n");

            bw.close();
            write.close();

            System.out.println("文件内容已更新成功。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/

}
